package cn.edu.jxau.test;

import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
 * @author Fudashi
 */
public class Main {

	public static void main(String[] args) throws InterruptedException, ExecutionException {

		Integer[] arr = new Integer[] { 1, 2, 3, 4 };
//		Integer[] arr = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		Node<Integer> head = toLinkedList(arr);
		System.out.println(delete(head, head.next.next.next));
		print(head);
	}

	private static <T> void print(Node<T> head) {

		Node<T> cur = head;
		while (cur != null) {
			System.out.print(cur.data + "\t");
			cur = cur.next;
		}
	}

	private static <T> Node<T> toLinkedList(T[] arr) {

		Objects.requireNonNull(arr, "参数arr不能为null");
		if (arr.length == 0) {
			return null;
		}

		Node<T> head = new Node<>(arr[0]);
		Node<T> cur = head;
		for (int i = 1; i < arr.length; i++) {
			Node<T> node = new Node<>(arr[i]);
			cur.next = node;
			cur = node;
		}
		return head;
	}

	private static <T> T delete(Node<T> head, Node<T> node) {

		Objects.requireNonNull(head, "参数head不能为null");
		Objects.requireNonNull(node, "参数node不能为null");
		T data = node.data;
		if (head == node) { // 如果要删除头结点
			head.data = null;
			head.next = null;
			return data;
		}
		if (node.next == null) { // 要删除最后一个节点只能遍历链表

			Node<T> cur = head;
			while (cur.next != node) {
				cur = cur.next;
			}
			cur.next = null;
		} else {
			node.data = node.next.data;
			node.next = node.next.next;
		}
		return data;
	}
}

class Node<T> {

	public T data;
	public Node<T> next;

	public Node() {

	}

	public Node(T data) {
		this.data = data;
	}
}